package com.wildlife.springboot.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wildlife.springboot.common.Result;
import com.wildlife.springboot.entity.Survive;
import com.wildlife.springboot.service.ISurviveService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/survive")
public class SurviveController {
    @Resource
    private ISurviveService surviveService;


    //新增和修改
    @PostMapping
    public Result save(@RequestBody Survive survive){
        //新增或更新
        return Result.success(surviveService.saveOrUpdate(survive));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(surviveService.removeById(id));
    }

    @PostMapping ("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(surviveService.removeByIds(ids));
    }

    @GetMapping
    public Result findAll() {
        return Result.success(surviveService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(surviveService.getById(id));
    }

    @GetMapping("/habitat/{habitat}")
    public Result findOne(@PathVariable String habitat) {
        QueryWrapper<Survive> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("habitat", habitat);
        return Result.success(surviveService.getOne(queryWrapper));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize
//                           @RequestParam(defaultValue = "") Integer id
    ) {
        QueryWrapper<Survive> queryWrapper = new QueryWrapper<>();
//        if (!"".equals(id)) {
//            queryWrapper.like("id", id);
//        }
        return Result.success(surviveService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    // 导出接口
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Survive> list = surviveService.list();
        // 通过工具类创建writer 写出到磁盘路径

        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("habitat", "栖息地");
        writer.addHeaderAlias("distribution", "分布");
        writer.addHeaderAlias("habit", "习性");
        writer.addHeaderAlias("altitude", "海拔");
        writer.addHeaderAlias("climate", "气候");
        writer.addHeaderAlias("dna", "DNA");

        writer.write(list, true);

        // 设置浏览器相应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("生存特点", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    // 导入接口
    // reader.addHeaderAlias(): 忽略表头的中文
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("ID", "id");
        reader.addHeaderAlias("栖息地", "habitat");
        reader.addHeaderAlias("分布", "distribution");
        reader.addHeaderAlias("习性", "habit");
        reader.addHeaderAlias("海拔", "altitude");
        reader.addHeaderAlias("气候", "climate");
        reader.addHeaderAlias("DNA", "dna");
        List<Survive> list = reader.readAll(Survive.class);
        surviveService.saveBatch(list);
        return true;
    }
}
